/**
 * 
 */
package cc.dogtailflower.framework.resultsetmapper;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cc.dogtailflower.framework.annotation.Entity;
import cc.dogtailflower.framework.handler.ModalReflectorHandler;

/**
 * 基于 注解的 结果集 映射 成bean
 * @author cc
 *
 */
public class ResultSetMapperImpl<T> implements ResultSetMapper<T>{

	@SuppressWarnings("unchecked")
	public List<T> resultSetToObject(ResultSet rs,Class<?> outputClass){
		List<T> outputList = new ArrayList<T>();
		try{
			if(rs != null){
				if(outputClass.isAnnotationPresent(Entity.class)){
					ResultSetMetaData rsmd = rs.getMetaData();
					while(rs.next()){
						Map<String,Object> map = new HashMap<String,Object>();
						Map<Class<?>,Map<String,String>> resultMap = ResultSetObjectMappingTable.getMap();
						Map<String,String> columnMap = resultMap.get(outputClass);
						for(int iterator =0;iterator < rsmd.getColumnCount();iterator++){
							String columnName = rsmd.getColumnName(iterator+1);
							Object columnValue = rs.getObject(iterator+1);
							String fieldName = columnMap.get(columnName);
							map.put(fieldName, columnValue);
						}
						T bean = (T)ModalReflectorHandler.bindModel(map, outputClass);
						outputList.add(bean);
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return outputList;
	}
}
